/**
 *====================================================
 * 文件名称: FinanceInsuranceActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月26日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.context.FinanceBaseAction;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.SignatureInfoEntity;
import com.yuexunit.finance.project.action.v1.dto.FinanceContractCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceLoanCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceMaterialCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceProcessCastor;
import com.yuexunit.finance.project.action.v1.model.Insurance;
import com.yuexunit.finance.project.action.v1.model.input.InsuranceCoverageParams;
import com.yuexunit.finance.project.action.v1.model.input.InsuranceUpdateParams;
import com.yuexunit.finance.project.action.v1.model.output.ConstractCallbackDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceContractDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceFilesInfoDetail;
import com.yuexunit.finance.project.action.v1.model.output.InsuranceCoverageDetail;
import com.yuexunit.finance.project.action.v1.model.output.InsuranceDetail;
import com.yuexunit.finance.project.action.v1.model.output.InsuranceLineInfo;
import com.yuexunit.finance.project.action.v1.model.output.SignFileSealInfoDetail;
import com.yuexunit.finance.project.action.v1.model.output.SupervisionContractDetail;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditEntity;
import com.yuexunit.finance.project.entity.FinanceConstractCallBackInfoEntity;
import com.yuexunit.finance.project.entity.FinanceContractEntity;
import com.yuexunit.finance.project.entity.FinanceFilesInfoEntity;
import com.yuexunit.finance.project.entity.FinanceMaterialEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementEntity;
import com.yuexunit.finance.project.entity.FinanceProcessEntity;
import com.yuexunit.finance.project.entity.InsuranceCoverageBulkstockEntity;
import com.yuexunit.finance.project.entity.InsuranceCoverageContainerEntity;
import com.yuexunit.finance.project.entity.InsuranceCoverageEntity;
import com.yuexunit.finance.project.entity.InsuranceEntity;
import com.yuexunit.finance.project.entity.SupervisionContractEntity;
import com.yuexunit.finance.project.entity.lexicon.ApiFinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ConstractStateEnum;
import com.yuexunit.finance.project.entity.lexicon.FileSignStateEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceConstractStateEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceSegmentEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.InsuranceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.PurchaseEnum;
import com.yuexunit.finance.project.service.FinanceConstractCallBackService;
import com.yuexunit.finance.project.service.FinanceFilesInfoService;
import com.yuexunit.finance.project.service.FinanceSignatureInfoService;
import com.yuexunit.finance.project.service.InsuranceCoverageBulkstockService;
import com.yuexunit.finance.project.service.InsuranceCoverageContainerService;
import com.yuexunit.finance.project.service.InsuranceCoverageService;
import com.yuexunit.finance.project.service.InsuranceService;
import com.yuexunit.finance.seal.entity.lexion.SignStateEnum;
import com.yuexunit.finance.system.action.v1.dto.SendLetterMessage;
import com.yuexunit.finance.system.entity.FinanceFilesNormEntity;
import com.yuexunit.finance.system.entity.SignFileInfoEntity;
import com.yuexunit.finance.system.entity.SignFileSealInfoEntity;
import com.yuexunit.finance.system.service.FinanceFilesNormService;
import com.yuexunit.finance.system.service.SignFileInfoService;
import com.yuexunit.finance.system.service.SignFileSealInfoService;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.fs.service.TransferService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

/**
 * @ClassName: FinanceInsuranceActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月26日 下午12:07:10
 */
@Implements(FinanceContractActionApi.class)
public class FinanceContractActionApiImpl extends FinanceBaseAction implements FinanceContractActionApi {

	public static Logger logger = LoggerFactory.getLogger(FinanceContractActionApiImpl.class);
	// 保险信息
	private InsuranceService insuranceService = ComponentFactory.loadClass(InsuranceService.class);

	private InsuranceCoverageService insuranceCoverageService = ComponentFactory.loadClass(InsuranceCoverageService.class);

	private InsuranceCoverageBulkstockService insuranceCoverageBulkstockService = ComponentFactory.loadClass(InsuranceCoverageBulkstockService.class);

	private InsuranceCoverageContainerService insuranceCoverageContainerService = ComponentFactory.loadClass(InsuranceCoverageContainerService.class);

	private FinanceConstractCallBackService financeConstractCallBackService = ComponentFactory.loadClass(FinanceConstractCallBackService.class);

	//	private FinanceSignatureInfoService financeSignatureInfoService=ComponentFactory.loadClass(FinanceSignatureInfoService.class);

	private FinanceFilesNormService financeFilesNormService = ComponentFactory.loadClass(FinanceFilesNormService.class);

	private FinanceFilesInfoService financeFilesInfoService = ComponentFactory.loadClass(FinanceFilesInfoService.class);

	private SignFileSealInfoService signFileSealInfoService = ComponentFactory.loadClass(SignFileSealInfoService.class);

	private SignFileInfoService signFileInfoService = ComponentFactory.loadClass(SignFileInfoService.class);

	private TransferService transferService = ComponentFactory.loadClass(TransferService.class);

	private String tmp = "客户(%s)融资(%s)目前处于融资审核环节对应的(%s)节点，请及时审批！";

	private void createFinanceMaterial(String materials, Long financeId, Long segmentId, FinanceSegmentEnum financeSegment) {
		List<FinanceMaterialEntity> materialList = financeMaterialService.inquireFinanceMaterialList(financeId, segmentId, financeSegment);
		Set<String> materialUuids = new HashSet<>();
		org.apache.commons.collections.CollectionUtils.addAll(materialUuids, materials.split(","));
		for (FinanceMaterialEntity me : materialList) {
			if (materialUuids.contains(me.getFileUuid())) {
				materialUuids.remove(me.getFileUuid());
			} else {
				financeMaterialService.deleteFinanceMaterial(me.getMaterialId());
			}
		}
		List<FinanceMaterialEntity> financeMaterialList = FinanceMaterialCastor.fromFinanceMaterialArray(financeId, segmentId, financeSegment, materialUuids.toArray(new String[materialUuids.size()]));
		for (FinanceMaterialEntity me : financeMaterialList) {
			financeMaterialService.createFinanceMaterial(me);
		}
	}

	@Transactional
	@Override
	public String createInsurance(Insurance params) {
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(params.getFinanceId());
		InsuranceEntity insurance = FinanceContractCastor.fromInsurance(finance, params);
		Long insuranceId = insuranceService.createFinanceInsurance(insurance);
		return insuranceId.toString();
	}

	@Transactional
	@Override
	public String createInsuranceCoverage(InsuranceCoverageParams params) {
		InsuranceEntity insurance = insuranceService.inquireInsuranceEntity(params.getInsuranceId());
		if (InsuranceStateEnum.WAIT_ACCEPT != insurance.getInsuranceState()) {
			throw new BusinessException("保单信息已经生效,无法修改");
		}
		InsuranceCoverageEntity coverage = FinanceContractCastor.fromInsuranceCoverage(insurance, params);
		Long insuranceCoverageId = insuranceCoverageService.createInsuranceCoverage(coverage);
		List<InsuranceCoverageBulkstockEntity> bulkstocks = FinanceContractCastor.fromInsuranceBulkstock(coverage, params);
		for (InsuranceCoverageBulkstockEntity entity : bulkstocks) {
			insuranceCoverageBulkstockService.createInsuranceCoverageBulkstock(entity);
		}
		List<InsuranceCoverageContainerEntity> containers = FinanceContractCastor.fromInsuranceContainer(coverage, params);
		for (InsuranceCoverageContainerEntity entity : containers) {
			insuranceCoverageContainerService.createInsuranceCoverageContainer(entity);
		}
		insurance.setTotalAmount(insurance.getTotalAmount().add(coverage.getInsuranceAmount()));
		insurance.setTotalPremium(insurance.getTotalPremium().add(coverage.getPremium()));
		insuranceService.renovateFinanceInsurance(insurance);
		return insuranceCoverageId.toString();
	}

	@Transactional
	@Override
	public void updateInsurance(InsuranceUpdateParams params) {
		InsuranceEntity persist = insuranceService.inquireInsuranceEntity(params.getInsuranceId());
		if (InsuranceStateEnum.WAIT_ACCEPT != persist.getInsuranceState()) {
			throw new BusinessException("保单信息已经生效,无法修改");
		}
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(params.getFinanceId());
		InsuranceEntity insurance = FinanceContractCastor.fromInsurance(finance, params);
		insurance.setInsuranceId(params.getInsuranceId());
		insuranceService.updateFinanceInsurance(insurance);
	}

	@Transactional
	@Override
	public void deleteInsuranceCoverage(Long insuranceCoverageId) {
		InsuranceCoverageEntity persist = insuranceCoverageService.inquireInsuranceCoverage(insuranceCoverageId);
		InsuranceEntity insurance = insuranceService.inquireInsuranceEntity(persist.getInsuranceId());
		if (InsuranceStateEnum.WAIT_ACCEPT != insurance.getInsuranceState()) {
			throw new BusinessException("保单信息已经生效,无法修改");
		}

		insuranceCoverageService.deleteInsuranceCoverage(persist);
		List<InsuranceCoverageBulkstockEntity> bulkstocks = insuranceCoverageBulkstockService.inquireCoverageBulkstockList(insuranceCoverageId);
		for (InsuranceCoverageBulkstockEntity bulkstock : bulkstocks) {
			insuranceCoverageBulkstockService.deleteInsuranceCoverageBulkstock(bulkstock);
		}
		List<InsuranceCoverageContainerEntity> containers = insuranceCoverageContainerService.inquireCoverageContainerList(insuranceCoverageId);
		for (InsuranceCoverageContainerEntity container : containers) {
			insuranceCoverageContainerService.deleteInsuranceCoverageContainer(container);
		}

		insurance.setTotalAmount(insurance.getTotalAmount().subtract(persist.getInsuranceAmount()));
		insurance.setTotalPremium(insurance.getTotalPremium().subtract(persist.getPremium()));
		insuranceService.renovateFinanceInsurance(insurance);
	}

	@Transactional
	@Override
	public void consentInsurance(Long insuranceId) {
		InsuranceEntity insurance = insuranceService.inquireInsuranceEntity(insuranceId);
		insurance.setInsuranceState(InsuranceStateEnum.EFFECT);
		// 代理模式需要生成客户付款单 平台收款单
		if (PurchaseEnum.AGENT == insurance.getPurchase()) { // 委托代理(平台付款单)
			// 投保人->平台
			FinanceMoneyStatementEntity statement = FinanceLoanCastor.fromAgentInsurance(insurance);
			financeMoneyStatementService.createFinanceMoneyStatement(statement);
		}
		// 平台->保险公司
		FinanceMoneyStatementEntity statement = FinanceLoanCastor.fromInsurance(insurance);
		financeMoneyStatementService.createFinanceMoneyStatement(statement);

		insurance.setAuditDate(DateUtil.now());
		insurance.setAuditor(FinanceSessionContext.getAccountFullName());
		insuranceService.renovateFinanceInsurance(insurance);
	}

	@Transactional
	@Override
	public void opposeInsurance(Long insuranceId, Integer overReson, String overRemark) {
		InsuranceEntity insurance = insuranceService.inquireInsuranceEntity(insuranceId);
		insurance.setInsuranceState(InsuranceStateEnum.REFUSE);
		insurance.setOverRemark(overRemark);
		insurance.setOverReson(overReson);
		insurance.setAuditDate(DateUtil.now());
		insurance.setAuditor(FinanceSessionContext.getAccountFullName());
		insuranceService.renovateFinanceInsurance(insurance);
	}

	@Override
	@Transactional
	public void auditInsurance(Long insuranceId, Boolean auditAdvice, String overRemark) {
		InsuranceEntity insurance = insuranceService.inquireInsuranceEntity(insuranceId);
		if (auditAdvice) {
			insurance.setInsuranceState(InsuranceStateEnum.EFFECT);
			if (PurchaseEnum.AGENT == insurance.getPurchase()) { // 委托代理(平台付款单)
				// 投保人->平台
				FinanceMoneyStatementEntity statement = FinanceLoanCastor.fromAgentInsurance(insurance);
				financeMoneyStatementService.createFinanceMoneyStatement(statement);
			}
			// 平台->保险公司
			FinanceMoneyStatementEntity statement = FinanceLoanCastor.fromInsurance(insurance);
			financeMoneyStatementService.createFinanceMoneyStatement(statement);
		} else {
			insurance.setInsuranceState(InsuranceStateEnum.REFUSE);
		}
		insurance.setAuditDate(DateUtil.now());
		insurance.setAuditor(FinanceSessionContext.getAccountFullName());
		insurance.setOverRemark(overRemark);
		insuranceService.renovateFinanceInsurance(insurance);
	}

	@Transactional
	@Override
	public void revokeInsuranceDetail(Long insuranceId, Integer overReson, String overRemark) {
		InsuranceEntity insurance = insuranceService.inquireInsuranceEntity(insuranceId);
		if (insurance.getAlreadyPremium().compareTo(BigDecimal.ZERO) > 0) {
			throw new BusinessException("保费已付，不能撤销！");
		}
		insurance.setInsuranceState(InsuranceStateEnum.REVOKE);
		insurance.setOverRemark(overRemark);
		insurance.setOverReson(overReson);
		insuranceService.renovateFinanceInsurance(insurance);
	}

	@Override
	public InsuranceDetail inquireInsuranceDetail(Long insuranceId) {
		InsuranceEntity entity = insuranceService.inquireInsuranceEntity(insuranceId);
		return FinanceContractCastor.toFinanceInsuranceDetail(entity);
	}

	@Override
	public InsuranceCoverageDetail inquireInsuranceCoverageDetail(Long insuranceCoverageId) {
		InsuranceCoverageEntity entity = insuranceCoverageService.inquireInsuranceCoverage(insuranceCoverageId);
		return FinanceContractCastor.toInsuranceCoverageDetail(entity);
	}

	@Override
	public PageList<InsuranceLineInfo> inquireInsurancePageList(String insuranceNumber, Long financeId, String financeNumber, String dateBegin, String dateEnd, String applicant,String coverageName,String insuranceCompany, Integer insuranceState, PageCriteria page) {
		Integer beginDate = DateUtil.parseDateInt(dateBegin);
		Integer endDate = DateUtil.parseDateInt(dateEnd);
		InsuranceStateEnum _state = null;
		if (insuranceState != null) {
			_state = InsuranceStateEnum.valueOf(insuranceState);
		}

		List<Long> insuranceCoverageIdList = new ArrayList<Long>();
		if (StringUtil.isNotBlank(coverageName)) {
			List<InsuranceCoverageEntity> insuranceCoverageEntities = insuranceCoverageService.inquireInsuranceCoverageByCoverageName(coverageName);
			for (InsuranceCoverageEntity insuranceCoverageEntity : insuranceCoverageEntities) {
				insuranceCoverageIdList.add(insuranceCoverageEntity.getInsuranceCoverageId());
			}
		}

		PageList<InsuranceEntity> pages = insuranceService.inquireInsuranceList(insuranceCoverageIdList,insuranceNumber, financeId, financeNumber, beginDate, endDate, applicant,coverageName,insuranceCompany, _state, page);
		PageList<InsuranceLineInfo> results = new PageList<>(page, pages.getTotalRecordCount());
		for (InsuranceEntity entity : pages) {
			results.add(FinanceContractCastor.toFinanceInsuranceLineInfo(entity));
		}
		return results;
	}

	// ========================================================================================================//
	@Transactional
	@Override
	public String createFinanceContract(Long financeId, String financeNumber, String contractSignDate, 
			String deliver, String receive, String financeContractSerialNumber, String materials, Long[] normId, String[] filesUuid, String[] filesSign, Integer contractType,
			String[] isSign, String signKey, String url, String imageNames) {

		FinanceContractEntity entity = FinanceContractCastor.fromFinanceContract(financeId, financeNumber, contractSignDate, deliver, receive, financeContractSerialNumber, contractType);
		Long financeContractId = financeContractService.createFinanceContract(entity);
		if (StringUtil.isNotBlank(materials)) {
			createFinanceMaterial(materials, entity.getFinanceId(), financeContractId, FinanceSegmentEnum.FINANCE_CONTRACT);
		}

		for (int i = 0; i < normId.length; i++) {
			if (StringUtil.isBlank(filesUuid[i])) {
				continue;
			}
			FinanceFilesNormEntity ffne = financeFilesNormService.inquireFinanceFilesNormDetail(normId[i]);
			FinanceFilesInfoEntity ffie = new FinanceFilesInfoEntity();
			ffie.setFilesUuid(filesUuid[i]);
			ffie.setFinanceId(financeId);
			ffie.setIsNotNull(ffne.getIsNotNull());
			ffie.setIsSign(ffne.getIsSign());
			ffie.setNormFileName(ffne.getNormFileName());
			ffie.setNormId(ffne.getNormId());
			if (contractType == 4) {
				ffie.setFinanceContractId(financeContractId);
			}
			financeFilesInfoService.createFinanceFilesInfo(ffie);


			String[] filesSigns = filesSign[i].split(",");
			String[] filesUuids = filesUuid[i].split(",");
			for (int j = 0; j< filesUuids.length; j++) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(filesUuids[j]);
				if (sfie == null) {
					sfie = new SignFileInfoEntity();
					sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
					sfie.setFileUuid(filesUuids[j]);
					sfie.setUpdateDateTime(DateUtil.now());
					sfie.setFilesSign(filesSigns[j]);
					signFileInfoService.createSignFileInfo(sfie);
				}
			}
		}

		// 项目状态更新
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if (contractType == 1) {
			financeEntity.setSupervisionContractId(financeContractId);
		} else if (contractType == 4) {
			financeEntity.setSupplementContractId(financeContractId);
			financeEntity.setFinanceState(FinanceStateEnum.LOANED);
			financeApplicationService.renovateFinanceApplication(financeEntity);
		} else {
			financeEntity.setFinanceContractId(financeContractId);
		}
		
		if (contractType != 4) {
			if (isSign != null && isSign.length > 0 && isSign[0].equals("1")) {
				financeEntity.setIsSign(Integer.valueOf(1));
			} else {
				financeEntity.setIsSign(Integer.valueOf(0));
			}
			financeEntity.setFinanceConstractState(FinanceConstractStateEnum.CONSTRACT_UPLOAD);
			financeApplicationService.renovateFinanceApplication(financeEntity);
			// 项目动态
			FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceContractProcess(financeId, financeNumber, financeContractId);
			financeProcessService.createFinanceProcess(financeProcessEntity);
		} else {
			
		}
		
		return financeContractId.toString();
	}

	@Override
	@Transactional
	public void callBackFinanceContract(Long financeId, String fileUuid, String remark) {

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);

		//		if (FinanceStateEnum.WAIT_PROTOCOL != financeEntity.getFinanceState()) {
		//			throw new BusinessException("审批通过的融资才能确认");
		//		}

		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid);
		if (FinanceSessionContext.isEnterprise()) {
			sfie.setFileSignState(FileSignStateEnum.CALLBACK_ENTERPRISE);
			sfie.setCallbackReamrk(sfie.getCallbackReamrk() + "发起人:"+FinanceSessionContext.getEnterpriseName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
		} else {
			if (financeEntity.getFinanceContractId() == null) {
				throw new BusinessException("合同还未提交,不允许打回");
			}
			//			if (ConstractStateEnum.CUSTOMER_CONTRACT_SUBMITED != financeEntity.getConstractState() && ConstractStateEnum.CONTRACT_SUBMITED != financeEntity.getConstractState()) {
			//				throw new BusinessException("合同还未提交,不允许打回");
			//			}
			sfie.setFileSignState(FileSignStateEnum.CALLBACK_PLATFORM);
			sfie.setCallbackReamrk(sfie.getCallbackReamrk() + "发起人:"+FinanceSessionContext.getAccountFullName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
		}
		signFileInfoService.updateSignFileInfo(sfie);

		//删除打回的签章记录
		List<SignFileSealInfoEntity> sfsies = signFileSealInfoService.inquireSignFileSealInfoList(fileUuid, null, null);
		for (SignFileSealInfoEntity sfsie : sfsies) {
			signFileSealInfoService.deleteSignFileSealInfo(sfsie.getSignFileSealId());
		}
		financeEntity.setConstractState(ConstractStateEnum.PROTOCOL_SUBMITED);
		financeEntity.setFinanceConstractState(FinanceConstractStateEnum.CALL_BACK);
		financeApplicationService.updateFinanceApplication(financeEntity);
	}

	@Override
	@Transactional
	public void replaceFinanceContract(Long financeId, String oldFileUuid, String newFileUuid, String remark) {
		FileEntry fe1 = transferService.inquireFileEntry(oldFileUuid);
		String filePath1 = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe1.getUri();

		//删除旧文件
		File oldFile = new File(filePath1);
		if (oldFile.exists() && oldFile.isFile()) {
			if (oldFile.delete()) {
				System.out.println("delete file:" + fe1.getFileName() + "successful!");
			} else {
				System.out.println("delete file:" + fe1.getFileName() + "failed!");
			}
		}
		//加入新文件

		FileEntry fe2 = transferService.inquireFileEntry(newFileUuid);
		String filePath2 = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe2.getUri();
		File newFile = new File(filePath2);
		copyFile(filePath2, oldFile.getParent() + "\\" + newFile.getName());

		BeanUtils.copyProperties(fe2, fe1, "fileUuid");
		PersistUtil.update(fe1);

		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(oldFileUuid);
		sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
		sfie.setUpdateReamark(sfie.getUpdateReamark() + "发起人:"+FinanceSessionContext.getAccountFullName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
		signFileInfoService.updateSignFileInfo(sfie);

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setFinanceConstractState(FinanceConstractStateEnum.CONSTRACT_UPLOAD);
		financeApplicationService.updateFinanceApplication(financeEntity);
	}

	private void copyFile(String oldPath, String newPath)  {    
		try  {    
			int byteread = 0;  
			File oldfile = new File(oldPath);  
			if (oldfile.exists()) {  //文件存在时
				InputStream inStream = new FileInputStream(oldPath);  //读入原文件   
				FileOutputStream fs = new FileOutputStream(newPath);    
				byte[] buffer = new byte[1024];    
				while ((byteread = inStream.read(buffer)) != -1) {  
					fs.write(buffer, 0, byteread);  
				}
				fs.close();
				inStream.close();    
			}    
		}
		catch  (Exception  e)  {    
			System.out.println("复制单个文件操作出错");    
			e.printStackTrace();    
		}    
	}


	@Override
	@Transactional
	public void changeFileSign(String fileUuid) {
		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid);
		if ("1".equals(sfie.getFilesSign())) {
			sfie.setFilesSign("0");
		} else {
			sfie.setFilesSign("1");
		}
		signFileInfoService.updateSignFileInfo(sfie);
	}

	@Override
	@Transactional
	public void confirmFinanceContract(String fileUuid, Long financeId) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);

		if (FinanceStateEnum.WAIT_PROTOCOL != financeEntity.getFinanceState()) {
			throw new BusinessException("审批通过的融资才能确认");
		}
		if (financeEntity.getFinanceContractId() == null) {
			throw new BusinessException("合同还未提交,不允许确认");
		}
		//		if (ConstractStateEnum.CUSTOMER_CONTRACT_SUBMITED != financeEntity.getConstractState() && ConstractStateEnum.CONTRACT_SUBMITED != financeEntity.getConstractState()) {
		//			throw new BusinessException("合同还未提交,不允许确认");
		//		}

		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid);
		sfie.setFileSignState(FileSignStateEnum.CONFIRM);
		signFileInfoService.updateSignFileInfo(sfie);

		FinanceContractDetail fcd = inquireFinanceContract(financeId, 2);
		Boolean flag = Boolean.TRUE;
		outer : for (FinanceFilesInfoDetail ffid : fcd.getFinanceFilesInfoList()) {
			for (String str : ffid.getFileSignState().split(",")) {
				if (!"6".equals(str)) {
					flag = Boolean.FALSE;
					break outer;
				}
			}
		}

		if (Boolean.TRUE == flag) {
			confirmContract(financeId, 2, "-");
		}
	}

	@Override
	public FinanceFilesInfoDetail inquireFinanceFilesInfoDetail(String fileUuid) {
		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid);
		FinanceFilesInfoDetail ffid = new FinanceFilesInfoDetail();
		BeanUtils.copyProperties(sfie, ffid);
		ffid.setFileSignState(String.valueOf(sfie.getFileSignState().ordinal()));
		return ffid;
	}

	/**客户签署融资合同**/
	@Override
	@Transactional
	public String signCustomerFinanceContract(Long financeContractId, Long financeId, String materials, String signKey, String url) {
		FinanceSignatureInfoService financeSignatureInfoService = ComponentFactory.loadClass(FinanceSignatureInfoService.class);

		// 项目状态更新
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if(!StringUtils.isEmpty(signKey)){  //判断是否做电子签章
			String [] imageUrls = materials.split(",");  //http pdf地址
			String [] imageName = null; //文件名
			if(imageUrls!=null && imageUrls.length > 0){
				String [] reurls = new String[imageUrls.length];
				imageName = new String[imageUrls.length];
				for(int i = 0; i < imageUrls.length; i++){
					SignatureInfoEntity bean = financeSignatureInfoService.inquireFinanceSignatureInfoEntity(imageUrls[i]);
					if(bean != null) {
						imageName[i]=bean.getFileName();
					}
					//reurls[i]="http://"+url+"/finance/api/1.0/downloadFile.file?fileUuid="+imageUrls[i];
					reurls[i] = ConfigPropertites.getProperties("UPLOAD_FILE22") + imageUrls[i];
				}
				//				materials = downloadFile(url, reurls, imageUrls, imageName, signKey, financeId, 1, financeEntity.getEnterpriseId());
			}
		}
		//更新文件记录
		createFinanceMaterial(materials, financeId, financeContractId, FinanceSegmentEnum.FINANCE_CONTRACT);
		//更新合同状态 
		financeEntity.setConstractState(ConstractStateEnum.CUSTOMER_CONTRACT_SUBMITED);
		financeEntity.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);   //待合同确认
		financeApplicationService.renovateFinanceApplication(financeEntity);
		return financeContractId.toString();
	}

	@Override
	@Transactional
	public void submitCustomerFinanceContract(Long financeId) {
		// 项目状态更新
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setConstractState(ConstractStateEnum.CUSTOMER_CONTRACT_SUBMITED);
		financeEntity.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);   //待合同确认
		financeEntity.setFinanceConstractState(FinanceConstractStateEnum.ENTERPRISE_SUBMIT);
		financeApplicationService.renovateFinanceApplication(financeEntity);
	}

	/** 
	 * @param type  1：客户   0：平台
	 * @return
	 * @return: String
	 */
	//	private static String downloadFile(String url, String[] reurls, String[] imageUrls, String[] imageName, String key, Long financeId, int type, Long enterpriseId) {
	//		if (reurls == null || reurls.length <= 0) {
	//			return null;
	//		}
	//
	//		StringBuffer sb = new StringBuffer();
	//		for(int i=0;i<reurls.length;i++){
	//			String fileUuid = reuploadFile(url, reurls[i], imageUrls[i], imageName[i], key, financeId, type, enterpriseId);
	//			if (fileUuid != null) {
	//				sb.append(fileUuid).append(",");
	//			}
	//		}
	//		return StringUtils.isEmpty(sb)?"":sb.substring(0,sb.length()-1).toString();
	//	}



	/** 
	 * @param type  1：客户   0：平台
	 * @return
	 * @return: String
	 */
	//	public static String reuploadFile(String url, String fileUrl, String imageUrl, String fileName, String key, Long financeId, int type, Long enterpriseId){
	//		FinanceSignatureActionApi financeSignatureActionApi = ComponentFactory.loadClass(FinanceSignatureActionApi.class);
	//		FinanceSignatureInfoService financeSignatureInfoService = ComponentFactory.loadClass(FinanceSignatureInfoService.class);
	//		FinanceSignatureService signatureService= ComponentFactory.loadClass(FinanceSignatureService.class);
	//		logger.info("+++fileUrl:" + fileUrl);
	//		FileEntry fileEntry = new FileEntry();
	//		TransferService fileService = ComponentFactory.loadClass(TransferService.class);
	//
	//		CloseableHttpClient httpclient = HttpClients.custom().build();
	//		HttpGet httpget = new HttpGet(fileUrl);
	//		CloseableHttpResponse response = null;
	//		try {
	//			response = httpclient.execute(httpget);
	//		} catch (ClientProtocolException e) {
	//			logger.error(e.getMessage());
	//		} catch (IOException e) {
	//			logger.error(e.getMessage());
	//		}
	//		ByteArrayOutputStream bytesm = new ByteArrayOutputStream();
	//		HttpEntity entity = response.getEntity();
	//		if (entity != null) {
	//			InputStream instream;
	//			try {
	//				instream = entity.getContent();
	//				byte []  buff = new byte[100];
	//				int rc = 0;
	//				while((rc = instream.read(buff)) != -1){
	//					bytesm.write(buff, 0, rc);
	//				}
	//			} catch (UnsupportedOperationException e) {
	//				e.printStackTrace();
	//			} catch (IOException e) {
	//				e.printStackTrace();
	//			}
	//			byte [] data =bytesm.toByteArray();
	//			//签署后的文档
	//			FileDigestSignResult result=null;
	//			if(type==0){ //平台
	//				result = financeSignatureActionApi.createSeflDocumentSummarySignStream(data, fileName, key);
	//				if(result.getErrCode() != 0){
	//					throw new BusinessException("平台签名失败!状态:" + result.getErrCode() + "msg:" + result.getMsg());
	//				}
	//			}else{ //客户签
	//				SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterpriseId, SealTypeEnum.ENTERPRISE);  //查询企业信息
	//				if (signatureEntity == null) {
	//					throw new BusinessException("客户签名失败!企业未注册e签宝");
	//				}
	//				result = financeSignatureActionApi.createDocumentSummarySignStream(enterpriseId, data, fileName, key);
	//				if(result.getErrCode()!=0){
	//					throw new BusinessException("客户签名失败!状态:"+result.getErrCode()+"msg:"+result.getMsg());
	//				}
	//			}
	//
	//			byte[] signDocment=result.getStream();
	//			//再次上传文件  获取文件名  和相关信息
	//			InputStream signInstream=new ByteArrayInputStream(signDocment);
	//			fileEntry = fileService.uploadFile(fileName, signInstream);
	//			String urls = "http://" + url + "/finance/data/" + fileEntry.getRelativePath();  //fileEntry.getServerAbsolutePath();   //文件物理路径
	//
	//			if(type==0){ //平台
	//				//记录文件相关信息，并 更新融资协议相关数据表  
	//				SignatureInfoEntity signatureInfoEntity = new SignatureInfoEntity(financeId, ApiTypeEnum.RZ.getCode(), fileName, fileEntry.getFileUuid(),
	//						"", null, FinanceSessionContext.getAccountId().toString(), new Date(), new Date());
	//				signatureInfoEntity.setPlatformFileUrl(urls);
	//				financeSignatureInfoService.createSignatureInfoEntity(signatureInfoEntity);
	//			}else{  //客户
	//				SignatureInfoEntity signatureInfoEntity=financeSignatureInfoService.inquireFinanceSignatureInfoEntity(imageUrl);
	//				signatureInfoEntity.setFileUuid(fileEntry.getFileUuid());
	//				signatureInfoEntity.setCustomerUserAccount(FinanceSessionContext.getAccountId().toString());
	//				signatureInfoEntity.setUserSignDate(new Date());
	//				//				    	signatureInfoEntity.setUserFileUrl(urls);
	//				signatureInfoEntity.setPlatformFileUrl(urls);
	//				financeSignatureInfoService.updateSignatureInfoEntity(signatureInfoEntity);
	//			}
	//			return fileEntry.getFileUuid();
	//		}
	//
	//		return null;
	//	}

	@Transactional
	@Override
	public void updateFinanceContract(Long financeContractId, String contractSignDate, String deliver, String receive,
			String financeContractSerialNumber, String materials,
			String[] isSign,String signKey,String url,String imageNames, Long[] filesInfoId, String[] filesUuid, String[] filesSign) {
		FinanceContractEntity persist = financeContractService.inquireFinanceContractEntity(financeContractId);

		FinanceContractEntity entity = FinanceContractCastor.fromFinanceContract(persist.getFinanceId(), persist.getFinanceNumber(), contractSignDate, deliver, receive, financeContractSerialNumber, null);
		entity.setFinanceContractId(financeContractId);

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(persist.getFinanceId());
		if (persist.getContractType() == 1 && ConstractStateEnum.PROTOCOL_SUBMITED == financeEntity.getConstractState()) {
			throw new BusinessException("协议已提交，不能再次修改");
		}
		if (persist.getContractType() == 2 && ConstractStateEnum.CONTRACT_SUBMITED == financeEntity.getConstractState()) {
			throw new BusinessException("合同已提交，不能再次修改");
		}
		if (isSign != null && isSign.length > 0 && isSign[0].equals("1")) {
			financeEntity.setIsSign(Integer.valueOf(1));
		} else {
			financeEntity.setIsSign(Integer.valueOf(0));
		}
		if (persist.getContractType() == 1) {
			financeEntity.setSupervisionContractId(financeContractId);
		} else {
			financeEntity.setFinanceContractId(financeContractId);
		}
		financeApplicationService.renovateFinanceApplication(financeEntity);
		financeContractService.updateFinanceContract(entity);
		createFinanceMaterial(materials, entity.getFinanceId(), financeContractId, FinanceSegmentEnum.FINANCE_CONTRACT);

		for (int i = 0; i < filesInfoId.length; i++) {
			FinanceFilesInfoEntity ffie = financeFilesInfoService.inquireFinanceFilesInfo(filesInfoId[i]);
			ffie.setFilesUuid(filesUuid[i]);
			financeFilesInfoService.updateFinanceFilesInfo(ffie);

			String[] filesSigns = filesSign[i].split(",");
			String[] filesUuids = filesUuid[i].split(",");
			for (int j = 0; j< filesUuids.length; j++) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(filesUuids[j]);
				if (sfie == null) {
					sfie = new SignFileInfoEntity();
					sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
					sfie.setFileUuid(filesUuids[j]);
					sfie.setUpdateDateTime(DateUtil.now());
					sfie.setFilesSign(filesSigns[j]);
					signFileInfoService.createSignFileInfo(sfie);
				} else {
					sfie.setFileUuid(filesUuids[j]);
					sfie.setUpdateDateTime(DateUtil.now());
					sfie.setFilesSign(filesSigns[j]);
					signFileInfoService.updateSignFileInfo(sfie);
				}
			}
		}
	}
	
	@Override
	public FinanceContractDetail inquireFinanceContractDetail(Long financeContractId) {
		FinanceContractEntity entity = financeContractService.inquireFinanceContractEntity(financeContractId);
		return FinanceContractCastor.toFinanceContractDetail(entity);
	}

	@Override
	public FinanceContractDetail inquireFinanceContract(Long financeId, Integer contractType) {
		FinanceContractEntity entity = financeContractService.inquireFinanceIdContract(financeId, contractType);
		return FinanceContractCastor.toFinanceContractDetail(entity);
	}

	// ========================================================================================================//
	@Transactional
	@Override
	public String createSupervisionContract(Long financeId, String financeNumber, String contractSignDate, Long logisticsCompanyId, String logisticsCompanyName, String materials) {
		if (supervisionContractService.inquireFinanceIdSupervisionContract(financeId) != null) {
			throw new BusinessException("已存在融资合同");
		}
		SupervisionContractEntity entity = FinanceContractCastor.fromSupervisionContract(financeId, financeNumber, contractSignDate, logisticsCompanyId, logisticsCompanyName);
		Long supervisionContractId = supervisionContractService.createSupervisionContract(entity);
		createFinanceMaterial(materials, entity.getFinanceId(), supervisionContractId, FinanceSegmentEnum.SUPERVISE_CONTRACT);

		// 融资监管合同ID回填
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setSupervisionContractId(supervisionContractId);
		financeApplicationService.renovateFinanceApplication(financeEntity);
		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromSupervisionContractProcess(financeId, financeNumber, supervisionContractId);
		financeProcessService.createFinanceProcess(financeProcessEntity);
		return supervisionContractId.toString();
	}

	@Transactional
	@Override
	public void updateSupervisionContract(Long supervisionContractId, String contractSignDate, Long logisticsCompanyId, String logisticsCompanyName, String materials) {
		SupervisionContractEntity persist = supervisionContractService.inquireSupervisionContractEntity(supervisionContractId);
		SupervisionContractEntity entity = FinanceContractCastor.fromSupervisionContract(persist.getFinanceId(), persist.getFinanceNumber(), contractSignDate, logisticsCompanyId, logisticsCompanyName);
		entity.setSupervisionContractId(supervisionContractId);
		supervisionContractService.updateSupervisionContract(entity);
		createFinanceMaterial(materials, entity.getFinanceId(), supervisionContractId, FinanceSegmentEnum.SUPERVISE_CONTRACT);
	}

	@Override
	public SupervisionContractDetail inquireSupervisionContractDetail(Long supervisionContractId) {
		SupervisionContractEntity entity = supervisionContractService.inquireSupervisionContractEntity(supervisionContractId);
		return FinanceContractCastor.toSupervisionContractDetail(entity);
	}

	@Override
	public SupervisionContractDetail inquireFinanceSupervisionContract(Long financeId) {
		SupervisionContractEntity entity = supervisionContractService.inquireFinanceIdSupervisionContract(financeId);
		return FinanceContractCastor.toSupervisionContractDetail(entity);
	}

	@Transactional
	@Override
	public void confirmContract(Long financeId, Integer contractType, String remark) {

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if (contractType == 1) {
			if (FinanceStateEnum.FIRSTCOMPLETE != financeEntity.getFinanceState()) {
				throw new BusinessException("初审通过的融资才能确认");
			}
			if (financeEntity.getSupervisionContractId() == null) {
				throw new BusinessException("协议还未提交,不允许确认");
			}
			if (ConstractStateEnum.PROTOCOL_SUBMITED != financeEntity.getConstractState()) {
				throw new BusinessException("协议还未提交,不允许确认");
			}
			financeEntity.setFinanceState(FinanceStateEnum.CONTRACT_SIGN);
			financeEntity.setConstractState(ConstractStateEnum.PROTOCOL_SUBMITED);
			if (financeEntity.getCallback() == Boolean.TRUE) {
				financeEntity.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);
			}
		} else {
			if (FinanceStateEnum.WAIT_PROTOCOL != financeEntity.getFinanceState()) {
				throw new BusinessException("审批通过的融资才能确认");
			}
			if (financeEntity.getFinanceContractId() == null) {
				throw new BusinessException("合同还未提交,不允许确认");
			}
			//查询是否采用电子签章流程
			//			List<SignatureInfoEntity> list=financeSignatureInfoService.inquireFinanceSignatureByFinanceIdList(financeId);
			//			if(list==null || list.size()==0){
			//				//以前流程
			//				if (ConstractStateEnum.CONTRACT_SUBMITED != financeEntity.getConstractState()) {
			//					throw new BusinessException("合同还未提交,不允许确认");
			//				}
			//			}else{
			//				//电子签章流程
			//				if (ConstractStateEnum.CUSTOMER_CONTRACT_SUBMITED != financeEntity.getConstractState()) {
			//					throw new BusinessException("客户合同还未提交,不允许确认");
			//				}
			//			}
			if (ConstractStateEnum.CUSTOMER_CONTRACT_SUBMITED != financeEntity.getConstractState() && ConstractStateEnum.CONTRACT_SUBMITED != financeEntity.getConstractState()) {
				throw new BusinessException("合同还未提交,不允许确认");
			}
			financeEntity.setConstractState(ConstractStateEnum.CONTRACT_SUBMITED);
			financeEntity.setFinanceState(FinanceStateEnum.WAIT_APPROVE);  //待正审
		}
		FinanceContractEntity fce = financeContractService.inquireFinanceIdContract(financeId, contractType);
		fce.setRemark(remark);
		financeContractService.updateFinanceContract(fce);
		financeEntity.setConstractCreateDatetime(null);
		financeEntity.setReceiveCreateDatetime(DateUtils.now());
		financeEntity.setFinanceConstractState(FinanceConstractStateEnum.WAIT_PLATFORM_SIGN);
		financeApplicationService.renovateFinanceApplication(financeEntity);

		FinanceAuditEntity fae = financeAuditService.inquireLatestFinanceAudit(financeEntity.getFinanceId());
		fae.setFinalState(ApiFinanceStateEnum.FK.getCode());
		//消息推送-风控审核
		SendLetterMessage.sendLetterMessage("riskAudit_1", String.format(tmp, financeEntity.getEnterpriseName(), financeEntity.getFinanceNumber(), "风控审核"));

		financeAuditService.updateFinanceAuditEntity(fae);
	}

	@Override
	@Transactional
	public void callBackContract(Long financeId, Long financeContractId, String callBackReason, String callBackRemark, Integer contractType) {
		//创建打回信息
		FinanceConstractCallBackInfoEntity entity = new FinanceConstractCallBackInfoEntity();
		entity.setFinanceId(financeId);
		entity.setCallBackReason(callBackReason);
		entity.setCallBackRemark(callBackRemark);
		entity.setOperator(FinanceSessionContext.getAccountFullName());
		entity.setCallBackDateTime(DateUtil.now());
		entity.setFinanceContractId(financeContractId);
		financeConstractCallBackService.createAbnormalBlame(entity);

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);

		if (contractType == 1) {
			if (FinanceStateEnum.FIRSTCOMPLETE != financeEntity.getFinanceState()) {
				throw new BusinessException("初审通过的融资才能打回");
			}
			if (ConstractStateEnum.PROTOCOL_SUBMITED != financeEntity.getConstractState()) {
				throw new BusinessException("协议还未提交,不允许打回");
			}
		} else {
			if (FinanceStateEnum.WAIT_PROTOCOL != financeEntity.getFinanceState()) {
				throw new BusinessException("审批通过的融资才能打回");
			}
			if (ConstractStateEnum.CUSTOMER_CONTRACT_SUBMITED != financeEntity.getConstractState() && ConstractStateEnum.CONTRACT_SUBMITED != financeEntity.getConstractState()) {
				throw new BusinessException("合同还未提交,不允许打回");
			}
			//			if (ConstractStateEnum.CONTRACT_SUBMITED != financeEntity.getConstractState()) {
			//				throw new BusinessException("合同还未提交,不允许打回");
			//			}
		}
		if (contractType == 1) {
			financeEntity.setConstractState(ConstractStateEnum.UNSUBMIT);
		} else {
			financeEntity.setConstractState(ConstractStateEnum.PROTOCOL_SUBMITED);
		}
		financeEntity.setFinanceConstractState(FinanceConstractStateEnum.CALL_BACK_ALL);
		financeApplicationService.renovateFinanceApplication(financeEntity);
	}

	@Override
	public PageList<ConstractCallbackDetail> inquireCallBackContractPageList(PageCriteria page) {
		PageList<FinanceConstractCallBackInfoEntity> pages = financeConstractCallBackService.inquireCallBackInfoPageList(null, page);
		PageList<ConstractCallbackDetail> results = new PageList<>(page, pages.getTotalPageCount());
		for (FinanceConstractCallBackInfoEntity fccie : pages) {
			ConstractCallbackDetail detail = FinanceContractCastor.toConstractCallbackDetail(fccie);
			results.add(detail);
		}
		return results;
	}

	@Override
	public ConstractCallbackDetail inquireCallBackContractDetail(Long callBackId) {
		FinanceConstractCallBackInfoEntity entity = financeConstractCallBackService.inquireCallBackInfoDetail(callBackId);
		ConstractCallbackDetail detail = FinanceContractCastor.toConstractCallbackDetail(entity);
		return detail;
	}

	@Override
	@Transactional
	public void uploadFinanceConstractSample(Long financeId, String financeConstractSample) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setFinanceConstractSample(financeConstractSample);
		financeApplicationService.renovateFinanceApplication(financeEntity);
	}

	@Override
	public PageList<SignFileSealInfoDetail> inquireSignFileSealInfoPageList(String fileUuid, Integer signState, Boolean isAll, PageCriteria page) {
		Integer creatorType = null;
		if (isAll != null && Boolean.TRUE == isAll) {
			creatorType = null;
		}else if (FinanceSessionContext.isEnterprise()) {
			creatorType = 0;
		} else {
			creatorType = 1;
		}
		SignStateEnum signStateEnum = null;
		if (signState != null) {
			signStateEnum = SignStateEnum.valueOf(signState);
		}
		PageList<SignFileSealInfoEntity> pages = signFileSealInfoService.inquireSignFileSealInfoPageList(fileUuid, creatorType, signStateEnum, page);
		PageList<SignFileSealInfoDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (SignFileSealInfoEntity s : pages) {
			SignFileSealInfoDetail detail = new SignFileSealInfoDetail();
			BeanUtils.copyProperties(s, detail);
			detail.setSignState(s.getSignState().ordinal());
			detail.setSealType(s.getSealType().ordinal());
			results.add(detail);
		}
		return results;
	}

	@Override
	@Transactional
	public void submitContract(Long financeId, Integer contractType) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if (contractType == 1) {
			if (financeEntity.getSupervisionContractId() == null) {
				throw new BusinessException("协议还未提交,不允许确认");
			}
			if (financeEntity.getConstractState() == ConstractStateEnum.PROTOCOL_SUBMITED) {
				throw new BusinessException("不能重复提交！");
			}
			financeEntity.setConstractState(ConstractStateEnum.PROTOCOL_SUBMITED);
		} else {
			if (financeEntity.getFinanceContractId() == null) {
				throw new BusinessException("合同还未提交,不允许确认");
			}
			//查询是否采用电子签章流程
			//			List<SignatureInfoEntity> list=financeSignatureInfoService.inquireFinanceSignatureByFinanceIdList(financeId);

			if(1 != financeEntity.getIsSign()){
				//以前流程
				if (financeEntity.getConstractState() == ConstractStateEnum.CONTRACT_SUBMITED) {
					throw new BusinessException("不能重复提交！");
				}
				financeEntity.setConstractState(ConstractStateEnum.CONTRACT_SUBMITED);
				financeEntity.setFinanceConstractState(FinanceConstractStateEnum.WAIT_CONFIRM);
			}else{
				//电子签章流程 
				if (financeEntity.getConstractState() == ConstractStateEnum.PLATFORM_CONTRACT_SUBMITED) {
					throw new BusinessException("不能重复提交！");
				}

				FinanceContractDetail fcd = inquireFinanceContract(financeId, 2);
				Boolean flag = Boolean.TRUE;
				outer : for (FinanceFilesInfoDetail ffid : fcd.getFinanceFilesInfoList()) {
					String is[] = ffid.getIsSign().split(",");
					String fss[] = ffid.getFileSignState().split(",");
					for (int i = 0; i < is.length; i++) {
						//不需要签署或者需要签署但不是未签署状态
						if (!"1".equals(is[i]) || ("1".equals(is[i]) && !"0".equals(fss[i]))) {

						} else {
							flag = Boolean.FALSE;
							break outer;
						}
					}
				}

				if (Boolean.TRUE == flag) {
					financeEntity.setFinanceConstractState(FinanceConstractStateEnum.WAIT_CONFIRM);
					financeEntity.setConstractState(ConstractStateEnum.CONTRACT_SUBMITED);
					financeEntity.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);
				} else {
					financeEntity.setFinanceConstractState(FinanceConstractStateEnum.WAIT_ENTERPRISE_SIGN);
					financeEntity.setConstractState(ConstractStateEnum.PLATFORM_CONTRACT_SUBMITED);
					financeEntity.setFinanceState(FinanceStateEnum.CUSTOMER_DOCUMENT);  //待客户审核
				}
			}

		}
		financeApplicationService.renovateFinanceApplication(financeEntity);
	}
}
